package mo.offer_special;

import java.util.HashMap;
import java.util.Map;

/**
 * 最近最少使用缓存
 */
public class L031 {

    class DLinkNode {
        int key;
        int value;
        DLinkNode prev;
        DLinkNode next;

        public DLinkNode() {
        }

        public DLinkNode(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    private int capacity;
    private int size;
    private DLinkNode head, tail;
    private Map<Integer, DLinkNode> cache = new HashMap<>();

    public L031(int capacity) {
        this.size = 0;
        this.capacity = capacity;
        head = new DLinkNode();
        tail = new DLinkNode();
        head.next = tail;
        tail.prev = head;
    }

    public int get(int key) {
        DLinkNode node = cache.get(key);
        if (node == null) {
            return -1;
        } else {
            moveToHead(node);
        }
        return node.value;
    }


    public void put(int key, int value) {
        DLinkNode node = cache.get(key);
        if (node == null) {
            node = new DLinkNode(key, value);
            cache.put(key, node);
            addToHead(node);
            size++;
            if (size > capacity) {
                DLinkNode removedNode = removeTail();
                cache.remove(removedNode.key);
                size--;
            }
        } else {
            node.value = value;
            moveToHead(node);
        }
    }


    private void moveToHead(DLinkNode node) {
        removeNode(node);
        addToHead(node);
    }

    private DLinkNode removeTail() {
        DLinkNode node = tail.prev;
        removeNode(node);
        return node;
    }

    private void removeNode(DLinkNode node) {
        DLinkNode prev = node.prev;
        DLinkNode next = node.next;
        prev.next = next;
        next.prev = prev;
    }

    private void addToHead(DLinkNode node) {
        DLinkNode headNext = head.next;
        head.next = node;
        node.prev = head;
        node.next = headNext;
        headNext.prev = node;
    }

    public static void main(String[] args) {
        L031 test = new L031(2);
        test.put(1, 1);
        test.put(2, 2);
        test.get(1);
        test.put(3, 3);
        test.get(2);
    }
}
